package com.github.rpc4j.producer.network;

import static org.jboss.netty.channel.Channels.pipeline;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

import com.github.rpc4j.producer.core.Rpc4jProducerContext;

public class NettyProducer extends Producer {

	public NettyProducer(Rpc4jProducerContext context) {
		super(context);
	}

	@Override
	public void init() {
		ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
		
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = pipeline();
				pipeline.addLast("en", new ObjectEncoder());
				pipeline.addLast("de", new ObjectDecoder());
				pipeline.addLast("handler", new NettyProducerHandler(NettyProducer.this.context));
				return pipeline;
			}
		});
		bootstrap.bind(new InetSocketAddress(context.getConfig().getRpcPort()));
	}

}
